from django.shortcuts import render
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.hashers import make_password, check_password
from myadmin import  models

# 首页
def index(request):

    # 获取分类
    '''
    # [
        {name:手机,
        items:[
        {name:'魅族','sub':[{},{}]},
        {name:'魅蓝','sub':[{},{}]}

        ]
    '''

    # 获取所有二级分类

    erlist = models.Types.objects.exclude(pid=0)
    
    context = {'erlist':erlist}

    # 获取所有一级分类
    data = models.Types.objects.filter(pid=0)

    for x in data:
        x.items = models.Types.objects.filter(pid=x.id)

    context['tlist'] = data

    return render(request,'home/index.html',context)


# 列表
def goodslist(request,tid):
    ob = models.Types.objects.get(id=tid)
    # 判断当前是一级分了还是二级分类
    if ob.pid == 0:
        # 一级分类

        # 获取当前类的子类
        data = ob
        data.items = models.Types.objects.filter(pid=data.id)
        ids = []
        for x in data.items:
            ids.append(x.id)
        # 获取  所有 子类的商品
        data.goodslist = models.Goods.objects.filter(tid__in=ids)
        context = {'data':data}
    else:    
        
        # 获取当前类的父类
        data = models.Types.objects.get(id=ob.pid)
        # 获取当前类的子类
        data.items = models.Types.objects.filter(pid=data.id)
        
        # 获取  当前 二级类的商品
        data.goodslist = models.Goods.objects.filter(tid=ob.id)
    
    # 分配数据
    context = {'data':data,'ob':ob}
    # 加载模板
    return render(request,'home/list.html',context)

# 详情
def goodsinfo(request,gid):
    # 根据商品id获取数据对象
    ob = models.Goods.objects.get(id=gid)

    context= {'ob':ob}

    return  render(request,'home/info.html',context)

# 注册
def register(request):
    # 判断当前请求的方式
    if request.method == 'POST':
        try:
            # 接受数据
            data = request.POST.dict()
            data.pop('csrfmiddlewaretoken')

            # 验证手机验证码是否正确
            if request.session['msgcode'] != data['msgcode']:
                return HttpResponse('<script>alert("手机验证码错误");location.href="/register/"</script>')
            
            # 删除数据中的msgcode
            data.pop('msgcode')
      
            # 密码加密
            data['password'] = make_password(data['password'], None, 'pbkdf2_sha256')
            # 执行添加
            models.Users.objects.create(**data)
            # 跳转到列表页
            return HttpResponse('<script>alert("注册成功,请登录");location.href="/login/"</script>')
        except:
            return HttpResponse('<script>alert("注册失败");location.href="/register/"</script>')
    else:
        # 返回一个注册的页面
        return render(request,'home/register.html')


# 登录
def login(request):
    if request.method == 'POST':
        # 判断验证码是否正确
        if (request.POST['vcode']).upper() != (request.session.get('verifycode')).upper():
            return HttpResponse('<script>alert("验证码错误");location.href="/login/"</script>')
        try:
            # 根据手机号获取用户
            ob = models.Users.objects.get(phone=request.POST['phone'])
            # 验证密码
            if check_password(request.POST['password'],ob.password):
                # 执行登录
                request.session['VipUser'] = {'uid':ob.id,'username':ob.username,'phone':ob.phone,'status':ob.status}
                return HttpResponse('<script>alert("登录成功");location.href="/"</script>')
        except:
            pass
        # 执行登录
        return HttpResponse('<script>alert("用户名或密码错误");location.href="/login/"</script>')
    else:
        return render(request,'home/login.html')


# 退出登录
def logout(request):

    del request.session['VipUser']

    return HttpResponse('<script>alert("退出登录成功");location.href="/"</script>')

# 验证码
def verifycode(request):
    #引入绘图模块
    from PIL import Image, ImageDraw, ImageFont
    #引入随机函数模块
    import random
    #定义变量，用于画面的背景色、宽、高
    bgcolor = (random.randrange(20, 100), random.randrange(
       20, 100), 255)
    width = 100
    height = 25
    #创建画面对象
    im = Image.new('RGB', (width, height), bgcolor)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的point()函数绘制噪点
    for i in range(0, 100):
       xy = (random.randrange(0, width), random.randrange(0, height))
       fill = (random.randrange(0, 255), 255, random.randrange(0, 255))
       draw.point(xy, fill=fill)
    #定义验证码的备选值
    str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
    # str1 = '123456789'
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0, 4):
       rand_str += str1[random.randrange(0, len(str1))]
    #构造字体对象
    font = ImageFont.truetype('FreeMono.ttf', 23)
    #构造字体颜色
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    #绘制4个字
    draw.text((5, 2), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, 2), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, 2), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, 2), rand_str[3], font=font, fill=fontcolor)
    #释放画笔
    del draw
    #存入session，用于做进一步验证
    request.session['verifycode'] = rand_str
    #内存文件操作
    import io
    buf = io.BytesIO()
    #将图片保存在内存中，文件类型为png
    im.save(buf, 'png')
    #将内存中的图片数据返回给客户端，MIME类型为图片png
    return HttpResponse(buf.getvalue(), 'image/png')

# 手机验证码
def sendmsg(request):

    #接口类型：互亿无线触发短信接口，支持发送验证码短信、订单通知短信等。
    #账户注册：请通过该地址开通账户http://user.ihuyi.com/register.html
    #注意事项：
    #（1）调试期间，请用默认的模板进行测试，默认模板详见接口文档；
    #（2）请使用 用户名 及 APIkey来调用接口，APIkey在会员中心可以获取；
    #（3）该代码仅供接入互亿无线短信接口参考使用，客户可根据实际需要自行编写；
      
    #!/usr/local/bin/python
    #-*- coding:utf-8 -*-

    # import urllib2
    import urllib
    import json
    import random
    #用户名 查看用户名请登录用户中心->验证码、通知短信->帐户及签名设置->APIID
    account  = "C61527389" 
    #密码 查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
    password = "77cfd66cf94ef97aaadfc683a4cb274a"
    mobile = request.GET.get('phone')
    # 随机验证码
    code = str(random.randint(10000,99999))
    # 把验证码存入session
    request.session['msgcode'] = code
    text = "您的验证码是："+code+"。请不要把验证码泄露给其他人。"
    data = {'account': account, 'password' : password, 'content': text, 'mobile':mobile,'format':'json' }
    req = urllib.request.urlopen(
        url= 'http://106.ihuyi.com/webservice/sms.php?method=Submit',
        data= urllib.parse.urlencode(data).encode('utf-8')
    )
    content =req.read()
    res = json.loads(content.decode('utf-8'))
    print(res)
    return HttpResponse(res)



# 修改密码
def xxx(request):
    ob = models.Users.objects.get(id=7)
    ob.password = make_password('1234567',None,'pbkdf2_sha256')
    ob.save()
    return HttpResponse('xxx')